package com.javacasino.casino.util;

import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPool {
    //核心线程池大小
    private  int corePoolSize = 100;
    //最大线程池大小
    private int maximumPoolSize = 500;
    //线程最大空闲时间
    private long keepAliveTime = 100;
    //线程等待队列
    private BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5000);
    //线程创建工厂
    ThreadFactory threadFactory = new NameTreadFactory();
    //拒绝策略
    RejectedExecutionHandler handler = new MyIgnorePolicy();

    ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
            workQueue, threadFactory, handler);

     static {
         ThreadPool threadPool = new ThreadPool();
         // 预启动所有核心线程
         threadPool.executor.prestartAllCoreThreads();
     }

     //加入线程池
     public void placeOrder(ThreadTask thread){
         executor.submit(thread);
     }
    public void placeOrder(List<ThreadTask> thread){
        thread.forEach(t->{
            executor.submit(t);
        });
    }
    //加入线程池
    public Object placeOrder(ThreadCallable thread){
         try{
             Future submit = executor.submit(thread);
             Object o = submit.get();
             return o;
         }catch (Exception e){
             System.err.println(e);
         }
        return null;
    }
    static class NameTreadFactory implements ThreadFactory {
        /*
         * 是一个提供原子操作的Integer类，通过线程安全的方式操作加减。
         * 提供原子操作来进行Integer的使用，因此十分适合高并发情况下的使用。
         */
        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            System.out.println(t.getName() + " has been created 正在創建");
            return t;
        }
    }
    static class MyIgnorePolicy implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            doLog(r, e);
        }

        private void doLog(Runnable r, ThreadPoolExecutor e) {
            // 可做日志记录等
            System.err.println( r.toString() + " rejected+拒絕執行");
//          System.out.println("completedTaskCount: " + e.getCompletedTaskCount());
        }
    }
}

